package com.jyw.custom.sms.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.jyw.common.constant.CacheConstants;
import com.jyw.common.core.redis.RedisCache;
import com.jyw.common.exception.ServiceException;
import com.jyw.custom.sms.service.ISmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements ISmsService {
    @Resource
    private RedisCache redisCache;


    @Override
    public String sendCode(String phone) {
        //生成uuid
        String key = UUID.fastUUID().toString(true);
        String cacheKey = CacheConstants.SMS_CACHE_KEY + key;
        //生成验证码
        //生成6位数字
//        String code = RandomUtil.randomNumbers(6);
        String code = "123456";
        //todo 对接短信平台 发送短信
        //存入缓存,保存5分钟
        redisCache.setCacheObject(cacheKey,code,5, TimeUnit.MINUTES);
        return key;
    }

    @Override
    public boolean validateCode(String key, String code) {
        String cacheKey = CacheConstants.SMS_CACHE_KEY + key;
        if (!redisCache.hasKey(cacheKey)) {
            throw new ServiceException("验证码已过期");
        }
        String cacheCode = redisCache.getCacheObject(cacheKey);
        return cacheCode.equals(code);
    }
}
